package dxn.nl.file.biz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import dxn.nl.file.biz.dao.AppClientRegisterDao;
import dxn.nl.file.biz.po.AppClientRegisterPo;
import dxn.nl.file.biz.po.AppModelPo;
import dxn.nl.file.biz.po.FileDealServerPo;
import dxn.nl.file.biz.service.AppClientRegisterBaseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Slf4j
@Service
public class AppClientRegisterBaseServiceImpl extends ServiceImpl<AppClientRegisterDao, AppClientRegisterPo> implements AppClientRegisterBaseService {
    @Override
    public int saveAppClient(AppClientRegisterPo po) {
        try{
            LambdaQueryWrapper<AppClientRegisterPo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(AppClientRegisterPo::getAppId, po.getAppId())
                    .eq(AppClientRegisterPo::getIp, po.getIp())
                    .eq(AppClientRegisterPo::getPort, po.getPort());

            AppClientRegisterPo appModelPo = this.baseMapper.selectOne(lambdaQueryWrapper);
            if(appModelPo == null)
            {
                this.baseMapper.insert(po);
            }

            this.baseMapper.update(po,lambdaQueryWrapper);
        }
        catch (Exception ex)
        {
            log.error("保存注册客户端失败",ex);
        }
        return 0;
    }

    @Override
    public int removeAppClient(String appId, String sessionId) {
        try{
            LambdaQueryWrapper<AppClientRegisterPo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(AppClientRegisterPo::getAppId, appId)
                    .eq(AppClientRegisterPo::getSessionId, sessionId);

            return this.baseMapper.delete(lambdaQueryWrapper);
        }
        catch (Exception ex)
        {
            log.error("保存注册客户端失败",ex);
        }
        return 0;
    }

    @Override
    public int refreshAppClient(String appId, String sessionId, LocalDateTime time) {
        try{
            LambdaQueryWrapper<AppClientRegisterPo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(AppClientRegisterPo::getAppId, appId)
                    .eq(AppClientRegisterPo::getSessionId, sessionId);

            AppClientRegisterPo data = new AppClientRegisterPo();
            data.setRefreshTime(LocalDateTime.now());

            return this.baseMapper.update(data,lambdaQueryWrapper);
        }
        catch (Exception ex)
        {
            log.error("保存注册客户端失败",ex);
        }
        return 0;
    }
}
